Internal Optimization and Caching of Deterministic Functions in MySQL
MySQL can optimize the execution of deterministic functions because their output always depends only on their input values. This allows MySQL to cache or precompute results during query optimization and execution.
A deterministic function always returns the same result for the same input.
A non-deterministic function (e.g., NOW(), RAND()) may return different results on each call.
MySQL can only safely cache deterministic function results.
During query parsing, MySQL evaluates deterministic functions whose inputs are constants.
It replaces them with their computed literal values (constant folding).
This reduces repeated computation at runtime.
MySQL may compute a deterministic function once per row or once per statement depending on the context.
When the same expression appears multiple times in a query, MySQL avoids recomputing it.
Cached values may be reused within the same SELECT, JOIN, or WHERE clause.
User-defined stored functions can be declared DETERMINISTIC.
This allows the optimizer to apply constant folding and expression caching.
Without declaring DETERMINISTIC, MySQL assumes the function might change results and avoids optimizations.
Caching is only valid within the scope of a query—not across multiple queries.
MySQL does not maintain a global cache of function results.
Non-deterministic functions are never cached because doing so would break correctness.
In summary: MySQL optimizes deterministic functions through constant folding, expression caching, and use of the DETERMINISTIC keyword in stored functions. These optimizations reduce repeated computation and improve query performance.